package com.zhaoc.action;

import com.aliyuncs.exceptions.ClientException;
import com.zhaoc.domain.Customer;
import com.zhaoc.domain.constans.Constants;
import com.zhaoc.utils.BaseAction;
import com.zhaoc.utils.MailUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * <p>title:com.zhaoc.action</p>
 * date:2018/8/7 0007
 * time:21:20
 * author:&#x8d75;&#x6210;
 * user:13566
 */
@ParentPackage("json-default")
public class CustomerAction extends BaseAction<Customer> {

    //获取activemq的对象
    @Autowired
    @Qualifier("jmsQueueTemplate")
    private JmsTemplate jmsTemplate;

    //发送验证码的方法
    @Action(value = "customer_sendSms")
    public String sendCode() throws ClientException {
        //调用发短信的工具类
        //Map<String, String> map = SmsUtils.sendSms(model.getTelephone());
        //重构代码,先请求activemq,然后通过activemq调用发短信的类
        jmsTemplate.send("bos_sms", new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setString("telephone",model.getTelephone());
                return mapMessage;
            }
        });
        //把验证码存入session中
        //ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), map.get("code"));
        //判断是否发送成功
        return NONE;
    }

    //自动注入
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //用属性驱动获取前台的验证码
    private String checkcode;

    public void setCheckcode(String checkcode) {
        this.checkcode = checkcode;
    }

    //校验验证码
    @Action(value = "customer_regist", results = {@Result(name = SUCCESS, type = "redirect", location = "signup-success.html"),
            @Result(name = "input", type = "redirect", location = "signup.html")})
    public String customerRegist() {
        //首先判断验证码是否正确
        //先从session中获取先前存的验证码
        String checkcode2 = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
        if (checkcode2 == null || !checkcode.equalsIgnoreCase(checkcode2)) {
            //session中的验证码为空或者前台的验证码和后台的验证码不同,验证不通过
            System.out.println("验证码不通过");
            return INPUT;
        }
        //向webservice端发送请求传递客户信息进行保存
        WebClient.create("http://localhost:9002/crm_management/services/customerService/customer")
                .type(MediaType.APPLICATION_JSON)
                .post(model);
        System.out.println("验证通过");
        //生成一个邮件验证码
        String activeCode = RandomStringUtils.randomNumeric(23);
        //将验证码存进redis,期限设置为24小时
        redisTemplate.opsForValue().set(model.getTelephone(),activeCode,24,TimeUnit.HOURS);
        //调用邮件工具类发送邮件
        MailUtils.sendMail("邮箱验证",model.getEmail(),model.getTelephone(),activeCode);

        return SUCCESS;
    }

    //属性驱动获取前台传过来的验证码
    private String activecode;

    public void setActivecode(String activecode) {
        this.activecode = activecode;
    }

    //激活邮箱
    @Action(value = "customer_activeMail",results = {
                    @Result(name = SUCCESS,type = "redirect",location = "login.html")})
    public String customerActiveMail() throws IOException {
        //解决回写到浏览器乱码的问题
        ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
        //先从redis中获取验证码,看看是否有效
        String acCode = redisTemplate.opsForValue().get(model.getTelephone());
        if (acCode == null || !acCode.equals(activecode)){
            //验证码已失效,或验证码不正确
            ServletActionContext.getResponse().getWriter().println("激活链接已失效,请重新激活.");
            return NONE;
        }
        //防止重复绑定,先查询一下,是否已经激活邮箱
        Customer customer = WebClient.create("http://localhost:9002/crm_management/services/customerService/customer/telephone/"
                + model.getTelephone())
                .type(MediaType.APPLICATION_JSON)
                .get(Customer.class);
        if (customer.getType() == null || customer.getType() != 1){
            //邮箱没有激活,则向后台发请求激活
            WebClient.create("http://localhost:9002/crm_management/services/customerService/customer/updateType/"
                    +model.getTelephone()).get();
            ServletActionContext.getResponse().getWriter().println("邮箱绑定成功");
            return SUCCESS;

        }else {
            //账户已经激活
            ServletActionContext.getResponse().getWriter().println("您的邮箱已经激活,无须重复激活!");
            return NONE;
        }

    }



    //登陆方法
    @Action(value = "customer_login",results = {@Result(name = SUCCESS,type = "redirect",location = "index.html#/myhome"),
                                                @Result(name = "login",type = "redirect",location = "login.html")})
    public String login(){
        //向crm_management项目发送webservice请求,查询用户
        Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_HOST +
                "/crm_management/services/customerService/customer/login?telephone="
                + model.getTelephone() + "&password="
                + model.getPassword()).accept(MediaType.APPLICATION_JSON)
                .get(Customer.class);
        //判断是否查询到客户
        if (customer == null){
            //用户名或密码部队
            return "login";
        }
        //登陆成功以后将客户信息存入session中
        ServletActionContext.getRequest().getSession().setAttribute("customer",customer);
        return SUCCESS;
    }



}

